<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,100分)- 最长连续子序列（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h3 id="main-toc">题目描述</h3> 
<p>有N个正整数组成的一个序列。给定整数sum&#xff0c;求长度最长的连续子序列&#xff0c;使他们的和等于sum&#xff0c;返回此子序列的长度&#xff0c;</p> 
<p>如果没有满足要求的序列&#xff0c;返回-1。</p> 
<p></p> 
<h3 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h3> 
<p>第一行输入是&#xff1a;N个正整数组成的一个序列</p> 
<p>第二行输入是&#xff1a;给定整数sum</p> 
<p></p> 
<h3 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h3> 
<p>最长的连续子序列的长度</p> 
<p></p> 
<h3>备注</h3> 
<ul><li>输入序列仅由数字和英文逗号构成&#xff0c;数字之间采用英文逗号分隔</li><li>序列长度&#xff1a;1 &lt;&#61; N &lt;&#61; 200</li><li>输入序列不考虑异常情况</li></ul> 
<p></p> 
<h3 id="%E7%94%A8%E4%BE%8B">用例</h3> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;"> <p>1,2,3,4,2<br /> 6</p> </td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">3</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">1,2,3和4,2两个序列均能满足要求&#xff0c;所以最长的连续序列为1,2,3&#xff0c;因此结果为3。</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">1,2,3,4,2<br /> 20</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">-1</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">没有满足要求的子序列&#xff0c;返回-1</td></tr></tbody></table> 
<p></p> 
<h3>前缀和解法</h3> 
<p>本题数量级不大&#xff0c;可以考虑求解输入序列的前缀和数组&#xff0c;实现O(1)时间复杂度计算任意区间和&#xff0c;关于前缀和可以看&#xff1a;<a href="https://fcqian.blog.csdn.net/article/details/128976936" rel="nofollow" title="算法设计 - 前缀和 &amp; 差分数列_伏城之外的博客-CSDN博客">算法设计 - 前缀和 &amp; 差分数列_伏城之外的博客-CSDN博客</a></p> 
<p></p> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">const rl &#61; require(&#34;readline&#34;).createInterface({ input: process.stdin });
var iter &#61; rl[Symbol.asyncIterator]();
const readline &#61; async () &#61;&gt; (await iter.next()).value;

void (async function () {
  const nums &#61; (await readline()).split(&#34;,&#34;).map(Number);
  const target &#61; parseInt(await readline());

  console.log(getResult(nums, target));
})();

function getResult(nums, target) {
  const n &#61; nums.length;

  const preSum &#61; new Array(n &#43; 1).fill(0);
  for (let i &#61; 1; i &lt;&#61; n; i&#43;&#43;) {
    preSum[i] &#61; preSum[i - 1] &#43; nums[i - 1];
  }

  let maxLen &#61; -1;
  for (let l &#61; 0; l &lt;&#61; n - 1; l&#43;&#43;) {
    for (let r &#61; l &#43; 1; r &lt;&#61; n; r&#43;&#43;) {
      if (preSum[r] - preSum[l] &#61;&#61; target) {
        maxLen &#61; Math.max(maxLen, r - l);
      }
    }
  }

  return maxLen;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34;,&#34;)).mapToInt(Integer::parseInt).toArray();
    int target &#61; Integer.parseInt(sc.nextLine());

    System.out.println(getResult(nums, target));
  }

  public static int getResult(int[] nums, int target) {
    int n &#61; nums.length;

    // 前缀和数组
    int[] preSum &#61; new int[n &#43; 1];
    for (int i &#61; 1; i &lt;&#61; n; i&#43;&#43;) {
      preSum[i] &#61; preSum[i - 1] &#43; nums[i - 1];
    }

    // 记录最长连续子序列的长度
    int maxLen &#61; -1;

    // 求解所有连续子序列的区间和
    for (int l &#61; 0; l &lt;&#61; n - 1; l&#43;&#43;) {
      for (int r &#61; l &#43; 1; r &lt;&#61; n; r&#43;&#43;) {
        if (preSum[r] - preSum[l] &#61;&#61; target) {
          maxLen &#61; Math.max(maxLen, r - l);
        }
      }
    }

    return maxLen;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
nums &#61; list(map(int, input().split(&#34;,&#34;)))
target &#61; int(input())


# 算法入口
def getResult():
    n &#61; len(nums)

    preSum &#61; [0] * (n &#43; 1)
    for i in range(1, n &#43; 1):
        preSum[i] &#61; preSum[i - 1] &#43; nums[i - 1]

    maxLen &#61; -1

    for l in range(0, n):
        for r in range(l &#43; 1, n&#43;1):
            if preSum[r] - preSum[l] &#61;&#61; target:
                maxLen &#61; max(maxLen, r - l)

    return maxLen


# 算法调用
print(getResult())
</code></pre> 
<p></p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

#define MAX(a,b) (a) &gt; (b) ? (a) : (b)

#define MAX_SIZE 200

int getResult(int nums[], int nums_size, int target);

int main() {
    int nums[MAX_SIZE];
    int nums_size &#61; 0;

    while(scanf(&#34;%d&#34;, &amp;nums[nums_size&#43;&#43;])) {
        if(getchar() !&#61; &#39;,&#39;) break;
    }

    int target;
    scanf(&#34;%d&#34;, &amp;target);

    printf(&#34;%d\n&#34;, getResult(nums, nums_size, target));

    return 0;
}

int getResult(int nums[], int nums_size, int target) {
    int preSum[nums_size&#43;1];

    preSum[0] &#61; 0;
    for(int i&#61;1; i&lt;&#61;nums_size; i&#43;&#43;) {
        preSum[i] &#61; preSum[i-1] &#43; nums[i-1];
    }

    int maxLen &#61; -1;
    for(int l&#61;0; l&lt;&#61; nums_size-1; l&#43;&#43;) {
        for(int r&#61;l&#43;1; r &lt;&#61; nums_size; r&#43;&#43;) {
            if(preSum[r] - preSum[l] &#61;&#61; target) {
                maxLen &#61; MAX(maxLen, r - l);
            }
        }
    }

    return maxLen;
}</code></pre> 
<p></p> 
<p></p> 
<h3 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">双指针解法</h3> 
<p>本题可以利用双指针解决。</p> 
<p><img alt="" height="625" src="https://img-blog.csdnimg.cn/f67d43cc1c634c5a83b948c5e7261eb9.png" width="907" /></p> 
<p> 同时&#xff0c;有一种特殊情况</p> 
<p><img alt="" height="309" src="https://img-blog.csdnimg.cn/54d9956c4c654da796043efbbfc877a0.png" width="663" /></p> 
<p></p> 
<hr /> 
<p>2023.06.12</p> 
<p>本题的第二行输入是&#xff1a;给定整数sum</p> 
<p>因此sum可能取负数&#xff0c;0&#xff0c;正数&#xff0c;对于sum为负数&#xff0c;0的情况&#xff0c;可以直接返回-1&#xff0c;因为第一行输入是&#xff1a;N个正整数组成的一个序列</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 2) {
    const arr &#61; lines[0].split(&#34;,&#34;).map(Number);
    const sum &#61; parseInt(lines[1]);

    console.log(getMaxLen(arr, sum));

    lines.length &#61; 0;
  }
});

function getMaxLen(arr, sum) {
  let ans &#61; -1;

  if (sum &lt;&#61; 0) return ans;

  let l &#61; 0;
  let r &#61; 0;
  let n &#61; arr.length;

  let total &#61; arr[l];

  while (true) {
    if (total &gt; sum) {
      l&#43;&#43;;
      total -&#61; arr[l - 1];
      if (l &lt; n &amp;&amp; r &lt; l) {
        r &#61; l;
        total &#43;&#61; arr[r];
      }
    } else if (total &lt; sum) {
      r&#43;&#43;;
      if (r &lt; n) total &#43;&#61; arr[r];
      else break;
    } else {
      ans &#61; Math.max(ans, r - l &#43; 1);
      l&#43;&#43;;
      r&#43;&#43;;
      if (r &lt; n) total &#43;&#61; arr[r] - arr[l - 1];
      else break;
    }
  }

  return ans;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    Integer[] arr &#61;
        Arrays.stream(sc.nextLine().split(&#34;,&#34;)).map(Integer::parseInt).toArray(Integer[]::new);

    int sum &#61; Integer.parseInt(sc.nextLine());

    System.out.println(getResult(arr, sum));
  }

  public static int getResult(Integer[] arr, int sum) {
    int ans &#61; -1;
    if (sum &lt;&#61; 0) return ans;

    int l &#61; 0;
    int r &#61; 0;
    int n &#61; arr.length;

    int total &#61; arr[l];
    while (true) {
      if (total &gt; sum) {
        l&#43;&#43;;
        total -&#61; arr[l - 1];
        if (l &lt; n &amp;&amp; r &lt; l) {
          r &#61; l;
          total &#43;&#61; arr[r];
        }
      } else if (total &lt; sum) {
        r&#43;&#43;;
        if (r &lt; n) total &#43;&#61; arr[r];
        else break;
      } else {
        ans &#61; Math.max(ans, r - l &#43; 1);
        l&#43;&#43;;
        r&#43;&#43;;
        if (r &lt; n) total &#43;&#61; arr[r] - arr[l - 1];
        else break;
      }
    }

    return ans;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
arr &#61; list(map(int, input().split(&#34;,&#34;)))
sumV &#61; int(input())


# 算法入口
def getResult():
    ans &#61; -1

    if sumV &lt;&#61; 0:
        return ans

    l &#61; 0
    r &#61; 0
    n &#61; len(arr)

    total &#61; arr[l]

    while True:
        if total &gt; sumV:
            l &#43;&#61; 1
            total -&#61; arr[l - 1]
            if r &lt; l &lt; n:
                r &#61; l
                total &#43;&#61; arr[r]
        elif total &lt; sumV:
            r &#43;&#61; 1
            if r &lt; n:
                total &#43;&#61; arr[r]
            else:
                break
        else:
            ans &#61; max(ans, r - l &#43; 1)
            l &#43;&#61; 1
            r &#43;&#61; 1
            if r &lt; n:
                total &#43;&#61; arr[r] - arr[l - 1]
            else:
                break

    return ans


# 算法调用
print(getResult())
</code></pre> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

#define MAX(a, b) (a) &gt; (b) ? (a) : (b)

#define MAX_SIZE 200

int getResult(int nums[], int nums_size, int target);

int main() {
    int nums[MAX_SIZE];
    int nums_size &#61; 0;

    while (scanf(&#34;%d&#34;, &amp;nums[nums_size&#43;&#43;])) {
        if (getchar() !&#61; &#39;,&#39;) break;
    }

    int target;
    scanf(&#34;%d&#34;, &amp;target);

    printf(&#34;%d\n&#34;, getResult(nums, nums_size, target));

    return 0;
}

int getResult(int nums[], int nums_size, int target) {
    int maxLen &#61; -1;
    if (target &lt;&#61; 0) return maxLen;

    int l &#61; 0;
    int r &#61; 0;

    int sum &#61; nums[l];
    while (1) {
        if (sum &gt; target) {
            l&#43;&#43;;
            sum -&#61; nums[l - 1];

            if (l &lt; nums_size &amp;&amp; r &lt; l) {
                r &#61; l;
                sum &#43;&#61; nums[r];
            }
        } else if (sum &lt; target) {
            r&#43;&#43;;
            if (r &lt; nums_size) sum &#43;&#61; nums[r];
            else break;
        } else {
            maxLen &#61; MAX(maxLen, r - l &#43; 1);
            l&#43;&#43;;
            r&#43;&#43;;
            if (r &lt; nums_size) sum &#43;&#61; nums[r] - nums[l - 1];
            else break;
        }
    }

    return maxLen;
}</code></pre> 
<p></p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>